<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="hp" tagdir="/WEB-INF/tags/cover" %>

<link type="text/css" rel="stylesheet" href="${webroot}/madmin/vendors/bootstrap-datepicker/css/datepicker.css">
<link type="text/css" rel="stylesheet"
      href="${webroot}/madmin/vendors/bootstrap-daterangepicker/daterangepicker-bs3.css">
<link type="text/css" rel="stylesheet"
      href="${webroot}/madmin/vendors/bootstrap-timepicker/css/bootstrap-timepicker.min.css">
<style type="text/css">
    tr.detail-row {
        display: none;
    }

    tr.detail-row.open {
        display: block;
        display: table-row;
    }
</style>
<div class="panel panel-default new-add-brand">
    <div class="panel-heading">
        <c:if test="${empty parent}">
            <button class="btn btn-link pull-right" onclick="menuopen('/covers/${cover.id}.do');">返回首页详情</button>
        </c:if>
        <c:if test="${not empty parent}">
            <button class="btn btn-link pull-right" onclick="menuopen('/covers/${cover.id}/programs/${parent.id}.do');">
                返回
            </button>
        </c:if>
        <h3 class="panel-title">首页栏目管理</h3>
    </div>
    <form role="form" id="coverForm" class="form-horizontal form-bordered" onsubmit="return false;">
        <div class="panel-body pan">
            <div class="form-body pal">
                <div class="form-group">
                    <label for="name" class="col-md-2 control-label">名称:</label>
                    <div class="col-md-5">
                        <div class="input-icon">
                            <input name="name" id="name" type="text" placeholder="当前栏目模板的名称"
                                   class="form-control" value="${programDetail.program.name}" required>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-md-2 control-label">描述:</label>
                    <div class="col-md-5">
	                        <textarea name="description" id="description" rows="3" placeholder="栏目描述"
                                      class="form-control">${programDetail.program.description}</textarea>
                    </div>
                </div>

                <div class="form-group">
                    <label for="name" class="col-md-2 control-label">数据源标识:</label>
                    <div class="col-md-5">
                        <div class="input-icon">
                            <c:if test="${not empty programDetail.program.sourceId}">
                                <input name="sourceId" type="text" class="form-control" readonly="readonly"
                                       value="${programDetail.program.sourceId}" required>
                            </c:if>
                            <c:if test="${empty programDetail.program.sourceId}">
                                <input name="sourceId" type="text" class="form-control"
                                       value="${programDetail.program.sourceId}" required>
                            </c:if>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="name" class="col-md-2 control-label">生效时间:</label>
                    <div class="col-md-5">
                        <div>
                            <label class="line-height-1 blue">
                                <input name="timeRangePolicy" value="INHERIT" type="radio" class="ace time-range-policy"
                                ${programDetail.program.timeRangePolicy != 'STANDARD' ? 'checked' :''}>
                                <span class="lbl">继承上级</span>
                            </label>
                        </div>
                        <div>
                            <label class="line-height-1 blue">
                                <input name="timeRangePolicy" value="STANDARD" type="radio"
                                       class="ace time-range-policy"
                                ${programDetail.program.timeRangePolicy == 'STANDARD' ? 'checked' :''}>
                                <span class="lbl">自已定义</span>
                            </label>
                        </div>
                    </div>
                </div>
                <div class="form-group time-range-standard-container">
                    <label for="name" class="col-md-2 control-label">生效时间:</label>
                    <div class="col-md-2">
                        <div class="input-group bootstrap-timepicker timepicker">
                            <input name="startTime"
                                   value="<fmt:formatDate value="${programDetail.program.startTime}" pattern="yyyy-MM-dd HH:mm:ss"/>"
                                   class="form-control timepicker" type="text"/>
                        </div>
                    </div>
                    <div class="col-md-1 text-center">
                        -
                    </div>
                    <div class="col-md-2">
                        <input name="endTime"
                               value="<fmt:formatDate value="${programDetail.program.endTime}" pattern="yyyy-MM-dd HH:mm:ss"/>"
                               class="form-control timepicker" type="text"/>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-2 control-label">是否启用:</label>
                    <div class="col-md-10">
                        <c:choose>
                            <c:when test="${programDetail.program.status == 'ENABLE'}">
                                <input type="radio" name="status" value="ENABLE" checked="true">是
                                &nbsp;&nbsp;<input type="radio" name="status" value="DISABLE">否
                            </c:when>
                            <c:otherwise>
                                <input type="radio" name="status" value="ENABLE">是
                                &nbsp;&nbsp;<input type="radio" name="status" value="DISABLE" checked="true">否
                            </c:otherwise>
                        </c:choose>
                    </div>
                </div>
                <hr>
                <hp:coverTemplateData element="${programDetail.coverTemplateData}"
                                      fieldNamePrefix="coverTemplateData."/>
            </div>
        </div>
        <input type="hidden" name="id" value="${programDetail.program.id}">
        <input type="hidden" name="coverId" value="${cover.id}">
        <input type="hidden" name="parentId" value="${parent.id}">

        <div class="form-actions">
            <div class="col-md-offset-5 col-md-7">
                <button id="save" type="submit" class="btn btn-primary">
                    保存
                </button>
                <c:if test="${empty parent}">
                    <button type="button" class="btn btn-gray" onclick="menuopen('/covers/${cover.id}.do');">返回</button>
                </c:if>
                <c:if test="${not empty parent}">
                    <button type="button" class="btn btn-gray"
                            onclick="menuopen('/covers/${cover.id}/programs/${parent.id}.do');">返回
                    </button>
                </c:if>
            </div>
        </div>
    </form>
    <c:if test="${not empty programDetail.program.id}">
        <div class="panel-heading">
            <h3 class="panel-title">栏目子成员管理</h3>
        </div>
        <div class="text-right">
            <button type="button" class="btn btn-link"
                    onclick="menuopen('${webroot}/covers/${cover.id}/programs/new.do?parentId=${programDetail.program.id}');">
                <i class="fa fa-plus"></i>
                <span>新建栏目成员</span>
            </button>
        </div>
    </c:if>
    <c:if test="${not empty programDetail.subPrograms}">
        <table class="table table-bordered table-hover text-center">
            <thead>
            <tr>
                <th>成员ID</th>
                <th>名称</th>
                <th>描述</th>
                <th>状态</th>
                <th>生效时间</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
            <c:forEach items="${programDetail.subPrograms}" var="subProgram">
                <tr>
                    <td>${subProgram.sourceId}</td>
                    <td>${subProgram.name}</td>
                    <td>${subProgram.description}</td>
                    <td>${subProgram.status}</td>
                    <td>
                        <c:choose>
                            <c:when test="${subProgram.timeRangePolicy == 'STANDARD'}">
                                <fmt:formatDate value="${subProgram.startTime}" pattern="yyyy-MM-dd HH:mm:ss"/> 到
                                <fmt:formatDate value="${subProgram.endTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
                            </c:when>
                            <c:otherwise>
                                继承上级
                            </c:otherwise>
                        </c:choose>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-primary"
                                onclick="menuopen('/covers/${cover.id}/programs/${subProgram.id}.do');">
                            <i class="fa fa-icon fa-edit"></i>
                            编辑
                        </button>
                        <button class="btn btn-xs btn-danger"
                                onclick="deleteProgram('${subProgram.id}','${subProgram.name}')">
                            <i class="fa fa-icon fa-trash"></i>
                            删除
                        </button>
                    </td>
                </tr>
            </c:forEach>
            </tbody>
        </table>
    </c:if>
</div>

<script src="${webroot}/madmin/vendors/select2/select2.min.js"></script>
<script src="${webroot}/madmin/vendors/bootstrap-select/bootstrap-select.min.js"></script>
<script src="${webroot}/madmin/vendors/multi-select/js/jquery.multi-select.js"></script>
<script src="${webroot}/js/ui-dropdown-select.js"></script>
<script src="${webroot}/madmin/vendors/moment/moment.js"></script>
<script src="${webroot}/madmin/vendors/bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#coverForm").validate(
            {
                submitHandler: function (form) {
                    var url = "${webroot}/covers/${cover.id}/programs.do";
                    $.ajax({
                        cache: true,
                        type: "POST",
                        url: url,
                        data: $('#coverForm').serialize(),
                        async: false
                    }).done(function (data) {
                        layer.msg("保存成功");
                        console.log(data);
                        menuopen('${webroot}/covers/${cover.id}/programs/' + data + '.do');
                    }).fail(function () {
                        layer.msg("保存失败");
                    });
                }
            }
        );
        init();

    });

    function updateElementDataConfigContainerDisplayStatus() {
        var value = $('input.element-data-policy[type=radio]:checked').val();
        if (value == 'STATIC') {
            $(".dynamic-provider-container").hide();
            $(".static-elements-container").show();
        } else if (value == 'DYNAMIC') {
            $(".dynamic-provider-container").show();
            $(".static-elements-container").hide();
        }
    }

    function updateTimeRangePolicyContainerDisplayStatus() {
        var value = $('input.time-range-policy[type=radio]:checked').val();
        if (value == 'STANDARD') {
            $(".time-range-standard-container").show();
        } else if (value == 'INHERIT') {
            $(".time-range-standard-container").hide();
        }
    }

    function addCoverTemplateElement() {
        console.log("add CoverTemplateEmement");
        var orderIndex = $("#elements-table tbody tr").size() / 2;
        $.get("${webroot}/covers/programs/elements.do?index=" + orderIndex, function (elementTr) {
            $("#elements-table tbody").append(elementTr);
        });
    }

    function updateElementDataConfigContainerDisplayStatus(toggle) {
        console.log(toggle);
        console.log("切换集合数据加载方式");
        var $toggle = toggle ? $(toggle) : $('input.element-data-policy[type=radio]:checked:first');
        var value = $toggle.val() || $('input.element-data-policy[type=radio]:checked:first').val();
        var parentOfToggle = $toggle.closest(".form-group").parent();
        console.log(parentOfToggle);
        if (value == 'STATIC') {
            parentOfToggle.children(".dynamic-provider-container:first").hide();
            parentOfToggle.children(".static-elements-container:first").show();
        } else if (value == 'DYNAMIC') {
            parentOfToggle.children(".dynamic-provider-container:first").show();
            parentOfToggle.children(".static-elements-container:first").hide();
        }
    }

    function addCoverTemplateElement(toggle) {
        var $toggle = $(toggle);
        var fieldNamePrefix = $toggle.data("field-name-prefix");
        var orderIndex = $toggle.parent().find("table:first>tbody:first>tr").size() / 2;
        $.get("${webroot}/covers/programs/elements.do?index=" + orderIndex + "&fieldNamePrefix=" + fieldNamePrefix, function (elementTr) {
            $(toggle).parent().find("table:first>tbody:first").append(elementTr);
            init();
        });
    }

    function showCoverElementDetails(e) {
        var $this = $(e);
        var $nextTr = $this.closest('tr').next();
        $nextTr.toggleClass('open');
        $this.find("i.fa").toggleClass('fa-angle-double-down').toggleClass('fa-angle-double-up');
        updateElementDataConfigContainerDisplayStatus($nextTr.find("input.element-data-policy:checked"));
    }

    function deleteCoverElementDetails(e) {
        if (confirm("您确定要删除该条数据")) {
            var $toggle = $(e);
            var currentTr = $toggle.closest('tr');
            currentTr.next().remove();
            currentTr.remove();
            var isToggle = true;
            var index = -1;
            $toggle.closest("table").find("tbody tr").each(function () {
                if (isToggle) {
                    $(this).find("td:first").html(++index)
                } else {
                    $(this).find("input").each(function () {
                        var $this = $(this);
                        $this.attr("name", $this.attr("name").replace(/\d/, index));
                    });
                }
                isToggle = !isToggle;
            });
        }
    }

    function deleteProgram(id, name) {
        if (confirm("您确定要删除成员:" + name)) {
            $.post("${webroot}/covers/${cover.id}/programs/delete.do?programId=" + id, function () {
                menuopen('/covers/${cover.id}/programs/${programDetail.program.id}.do');
            });
        }
    }

    var get_image_uri = function (image_name, image_container) {
        $.ajax({
            method: 'post',
            data: {image_name: image_name},
            url: "${webroot}/product/fileupload/preview.do"
        }).done(function (data) {
            image_container.prev().prev().prev().prop("src", data.uri);
            console.log(image_container.next());
            image_container.next().attr("value", data.uri);
        });
    };
    function init() {
        console.log("init");

        $('input.timepicker').datetimepicker({
            format: 'YYYY-MM-DD HH:mm:ss',//选择完日期后，input框里的时间值的格式
            startDate: new Date(),//开始日期时间，在此之前的都不可选，同理也有endDate
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            forceParse: 0,
            showMeridian: 1,
            sideBySide: true //可以同时选择日期和时间
        });
        $('input.element-data-policy[type=radio]').change(function () {
            updateElementDataConfigContainerDisplayStatus(this);
        });
        updateElementDataConfigContainerDisplayStatus();
        $('input.time-range-policy[type=radio]').change(function () {
            updateTimeRangePolicyContainerDisplayStatus();
        });
        updateTimeRangePolicyContainerDisplayStatus();


        $('.logo_button').on('click', function () {
            var logo_file = $(this).next().next();
            logo_file.click();
        });

        $('.del_logo_button').on('click', function () {
            $(this).next().next().attr("value", "");
            $(this).prev().prev().attr("src", "");
        });

        $('.logo_file').on('change', function () {
            var $this = $(this);
            var file = this.files[0];
            var formData = new FormData();
            formData.append('file', file);
            $.ajax({
                url: '/upload/execute.do',
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false
            }).done(function (res) {
                if (res.status == 'success') {
                    layer.msg("上传图片成功");
                    get_image_uri(res.name, $this);
                } else {
                    layer.msg("上传图片失败");
                }
            }).fail(function (res) {
                layer.msg("图片上传功能异常");
            });
        });

    }



</script>